package com.atguigu.windowFunction;

import com.atguigu.bean.HotItem;
import com.atguigu.bean.UserBehavior;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.Comparator;
import java.util.TreeSet;

/**
 * Created by RUI on 2021/6/17 17:41
 *
 * 最近1小时内点击量最多的前3个商品
 */
public class High_prj_hotItem {
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env
                .readTextFile("input/UserBehavior.csv")
                .map(line -> { // 对数据切割, 然后封装到POJO中
                    String[] split = line.split(",");
                    return new UserBehavior(Long.valueOf(split[0]), Long.valueOf(split[1]), Integer.valueOf(split[2]), split[3],
                            Long.parseLong(split[4]) * 1000);
                })
                .filter(data -> "pv".equals(data.getBehavior()))
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.
                                <UserBehavior>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                                .withTimestampAssigner(new SerializableTimestampAssigner<UserBehavior>() {
                                    @Override
                                    public long extractTimestamp(UserBehavior element, long recordTimestamp) {
                                        return element.getTimestamp();
                                    }
                                })
                )
                .keyBy(UserBehavior::getItemId)
//                .window(SlidingEventTimeWindows.of(Time.hours(1),Time.minutes(5)))
                .window(TumblingEventTimeWindows.of(Time.hours(1)))
                .aggregate(new AggregateFunction<UserBehavior, Long, Long>() {
                               @Override
                               public Long createAccumulator() {
                                   return 0L;
                               }

                               @Override
                               public Long add(UserBehavior value, Long acc) {
                                   return acc + 1;
                               }

                               @Override
                               public Long getResult(Long acc) {
                                   return acc;
                               }

                               @Override
                               public Long merge(Long a, Long b) {
                                   return null;
                               }
                           },
                        new ProcessWindowFunction<Long, HotItem, Long, TimeWindow>() {
                            @Override
                            public void process(Long key,
                                                Context ctx,
                                                Iterable<Long> elements,
                                                Collector<HotItem> out) throws Exception {

                                Long aLong = elements.iterator().next();
                                out.collect(new HotItem(key, aLong, ctx.window().getEnd()));

                            }
                        }

                )
                .keyBy(HotItem::getWindowEndTime)
                .process(new KeyedProcessFunction<Long, HotItem, String>() {

                    private ListState<HotItem> hotItemState;
                    private ValueState<Long> timeState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        timeState = getRuntimeContext().getState(new ValueStateDescriptor<Long>("timeState", Long.class));
                        hotItemState = getRuntimeContext().getListState(new ListStateDescriptor<HotItem>("hotItemState", HotItem.class));
                    }

                    @Override
                    public void processElement(HotItem hi, Context ctx, Collector<String> out) throws Exception {

                        if (timeState.value() == null) {//定时器时间，等每组(每个小时)的数据都到齐后 10s 后开始计算top3
                            Long windowEndTime = hi.getWindowEndTime();
                            ctx.timerService().registerEventTimeTimer(windowEndTime + 10000);

                            timeState.update(windowEndTime);
                        }

                        hotItemState.add(hi);

                    }

                    @Override
                    public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {

                        TreeSet<HotItem> hotItems = new TreeSet<>(new Comparator<HotItem>() {
                            @Override
                            public int compare(HotItem o1, HotItem o2) {
                                int i = o2.getCount().compareTo(o1.getCount());
                                return i == 0 ? 1 : i;// 因为点击量有可能重复, 为了能够存储重复数据,此处不能返回0
                            }
                        });

                        for (HotItem hotItem : hotItemState.get()) {
                            hotItems.add(hotItem);

                            if (hotItems.size() > 3) {
                                hotItems.pollLast();
                            }
                        }

                        // 取top3
                        StringBuilder msg = new StringBuilder();
                        msg
                                .append("-----------------------\n")
                                .append("窗口结束时间: ").append(timestamp - 10000).append("\n");

                        for (HotItem hotItem : hotItems) {
                            msg.append(hotItem).append("\n");
                        }

                        out.collect(msg.toString());

                    }
                })

                .print();
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
